package com.zimin.cloud.file.controller;

import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.model.Filters;
import com.zimin.cloud.file.controller.api.IGridFsController;
import com.zimin.cloud.mine.pojo.file.business.FaceBO;
import com.zimin.common.constant.StringPool;
import com.zimin.common.exception.GraceException;
import com.zimin.common.utils.FileUtils;
import com.zimin.shared.enums.ResponseStatusEnum;
import com.zimin.shared.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @author zimin
 * @since 2022/4/8 10:46 上午
 */
@Slf4j
@RestController
public class GridFsController implements IGridFsController {

    @Autowired
    private GridFSBucket gridFsBucket;

    @Override
    public Result uploadFace(FaceBO faceBO) {
        //获取图片的base64字符串
        var img64 = faceBO.getImg64();
        //将base64字符串转换为byte数组
        var bytes = DatatypeConverter.parseBase64Binary(img64.trim());
        //转换为输入流
        var byteArrayInputStream = new ByteArrayInputStream(bytes);
        //上传到gridFs中
        var fileId = gridFsBucket.uploadFromStream(faceBO.getUserId() + ".png", byteArrayInputStream);
        //获得文件在gridFs中的主键
        return Result.ok(fileId.toString());
    }


    @Override
    public void readInGridFs(String faceId, HttpServletResponse response) throws Exception {
        GraceException.isNull(faceId, ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        GraceException.isTrue(faceId.equalsIgnoreCase(StringPool.EMPTY), ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        // 1 从gridfs中读取
        var adminFace = readGridFsByFaceId(faceId);
        // 2 把人脸图片输出到浏览器
        FileUtils.downloadFileByStream(response, adminFace);
    }

    @Override
    public Result readFace64InGridFs(String faceId) throws Exception {
        var myFace = readGridFsByFaceId(faceId);
        var base64Face = FileUtils.fileToBase64(myFace);
        return Result.ok(base64Face);
    }

    private File readGridFsByFaceId(String faceId) throws FileNotFoundException {
        var gridFsFiles = gridFsBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        var gridFs = gridFsFiles.first();
        GraceException.isNull(gridFs, ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        var fileName = gridFs.getFilename();
        //获取文件流，保存文件到本地或者到服务器的临时目录
        var fileTemp = new File("/Users/zimin/Desktop/img");
        if (!fileTemp.exists()) {
            fileTemp.mkdirs();
        }
        var myFile = new File("/Users/zimin/Desktop/img/" + fileName);
        //创建文件输出流
        var fileOutputStream = new FileOutputStream(myFile);
        //下载到服务器或者本地
        gridFsBucket.downloadToStream(new ObjectId(faceId), fileOutputStream);
        return myFile;
    }
}
